using System;
using MyReactivity.Abstractions;

namespace MyReactivity
{
    public class ReactiveProperty<T> : IReadOnlyReactiveProperty<T>
    {
        protected T ProtectedValue;
        protected Func<T, T> ProtectedSetValueFunc;

        public ReactiveProperty() : this(default, null) { }
        public ReactiveProperty(T value) : this(value, null) { }
        public ReactiveProperty(Func<T, T> setValueFunc) : this(default, setValueFunc) { }
        public ReactiveProperty(T value, Func<T, T> setValueFunc)
        {
            ProtectedSetValueFunc = setValueFunc;
            ProtectedValue = value;
        }

        public T Value
        {
            get => ProtectedValue;
            set
            {
                ProtectedValue = ProtectedSetValueFunc == null ? value : ProtectedSetValueFunc(value);

                ValueChanged?.Invoke(ProtectedValue);
            }
        }

        public event Action<T> ValueChanged;
    }
}
